// const serverUrl = 'http://119.23.42.196:8080'
const serverUrl = 'http://127.0.0.1:8080'
// const serverUrl = 'https://www.fruit.com'
const OPENID_KEY = "userOpenId"

function generagteRequestFunction(type) {
  return function (url, reqData) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: serverUrl + url,
        data: reqData,
        method: type,
        success: requestHandle(resolve, reject),
        header: getHeader()
      })
    })

  }
}

function getHeader() {
  return {}
}

function requestHandle(resolve) {
  const SUCCESS_CODE = 200
  const NO_AUTH_COE = 401
  return res => {
    if (res.statusCode === SUCCESS_CODE) {
      resolve(res.data)
    }
  }
}

function getUserOpenId() {
  return new Promise((resolve, reject) => {
    if (wx.getStorageSync(OPENID_KEY)) {
      console.log('%cget user openid form local: ' + wx.getStorageSync(OPENID_KEY), 'color: orange')
      resolve(wx.getStorageSync(OPENID_KEY))
      return
    }
    wx.login({
      success: res => {
        generagteRequestFunction('GET')('/wx/openId/' + res.code).then(data => {
          console.log('%cget user openid form server: ' + data, 'color: blue')
          wx.setStorageSync(OPENID_KEY, data)
          resolve(data)
        })
      }
    })
  })
}

module.exports = {
  get: generagteRequestFunction('GET'),
  post: generagteRequestFunction('POST'),
  put: generagteRequestFunction('PUT'),
  delete: generagteRequestFunction('DELETE'),
  getUserOpenId: getUserOpenId,
  serverUrl: serverUrl
}
